package com.ivan.stu.notetool.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

import static android.os.Environment.MEDIA_MOUNTED;

/**
 * Created by IVAN on 2019/2/21.
 */

public class FileManager {

    private static final String TAG = FileManager.class.getName();

    private static String sRootPath;
    public static void init(Context context, String rootName) {
        if (sRootPath != null) return;
        String state = Environment.getExternalStorageState();
        if (state.equals(MEDIA_MOUNTED)) {
            File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
            File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
            if (!appCacheDir.exists()) {
                if (!appCacheDir.mkdirs()) {
                    Log.e(TAG, "Unable to create external cache directory");
                }
            }
            if (appCacheDir.exists()) {
                File rootDir = new File(appCacheDir, rootName);
                if (rootDir.exists()) {
                    sRootPath = rootDir.getAbsolutePath();
                } else {
                    if (rootDir.mkdirs()) {
                        sRootPath = rootDir.getAbsolutePath();
                        File nomedia = new File(rootDir, ".nomedia");
                        try {
                            if (!nomedia.exists() && !nomedia.createNewFile()) {
                                Log.e(TAG, ".nomedia file create failed, the reason is createNewFile() return false");
                            }
                        } catch (IOException e) {
                            Log.e(TAG, ".nomedia file create failed, the reason is IOException");
                            e.printStackTrace();
                        }
                    } else {
                        Log.e(TAG, rootName + " directory make failed");
                    }
                }
            }
        } else {
            Log.e(TAG, "Android system can not get SdCard");
        }
    }

    public static File getRootDir() {
        File dir = new File(sRootPath);
        if (!dir.exists() && dir.mkdirs()) ;
        return dir;
    }

    public static File getFile(File parent, String fileName) {
        return newFile(parent, null, fileName, false);
    }

    public static File getFile(File parent, String fileName, boolean createFile) {
        return newFile(parent, null, fileName, createFile);
    }

    public static File getFile(File parent, String dirName, String fileName) {
        return newFile(parent, dirName, fileName, false);
    }

    public static File getFile(File parent, String dirName, String fileName, boolean createFile) {
        return newFile(parent, dirName, fileName, createFile);
    }

    public static File getDir(File parent, String dirName) {
        return newFile(parent, dirName, null, false);
    }

    /**
     * 根据给出的目录，获取一个指定的文件对象
     *
     * @param parent     父目录文件对象
     * @param dirName    目录名，为null表示直接在parent下创建对象
     * @param fileName   文件名，为null表示返回目录
     * @param createFile 是否创建文件
     * @return 返回文件对象，为null表示文件或目录不存在
     */
    private synchronized static File newFile(File parent, String dirName, String fileName, boolean createFile) {

        if (parent == null){

            Log.e("parent",null);

        }
        if (parent != null && parent.exists()) {
            if (dirName == null) {
                if (fileName != null) {
                    File file = new File(parent, fileName);
                    if (createFile) {
                        return createFileOrNot(file);
                    } else {

                        Log.e("file","走的这");
                        return file;
                    }
                }
            } else {
                File dir = new File(parent, dirName);
                if (dir.exists()) {
                    if (fileName == null) {
                        return dir;
                    }
                    File file = new File(dir, fileName);
                    if (createFile) {
                        return createFileOrNot(file);
                    } else {
                        return file;
                    }
                } else {
                    if (dir.mkdirs()) {
                        if (fileName == null) {
                            return dir;
                        }
                        File file = new File(dir, fileName);
                        if (createFile) {
                            return createFileOrNot(file);
                        } else {
                            return file;
                        }
                    }
                }
            }
        }
        return null;
    }

    private static File createFileOrNot(File file) {
        if (file.exists()) {
            return file;
        } else {
            try {
                if (file.createNewFile()) {
                    return file;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static boolean deleteFile(File file) {
        if (file != null && file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
            return !file.exists();
        }
        return true;
    }

    public static long getSize(File file) {
        if (file == null || !file.exists()) {
            return 0;
        }
        long size = 0;
        if (file.isFile()) {
            size += file.length();
        } else if (file.isDirectory()) {
            File[] fs = file.listFiles();
            for (int i = 0; i < fs.length; i++) {
                File f = fs[i];
                size += getSize(f);
            }
        }
        return size;
    }

    public static String getFileSize(File file) {
        long len = getSize(file);
        final int size_of_kb = 1024, size_of_mb = 1024 * size_of_kb;
        String unit = null;
        double finalLen = 1.0 * len / size_of_kb;
        if (finalLen >= 1024) {
            finalLen = 1.0 * len / size_of_mb;
            unit = "MB";
        } else {
            unit = "KB";
        }
        if (finalLen == (int) finalLen) {
            return (int) finalLen + unit;
        }
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(finalLen) + unit;
    }

}
